package com.school.edupoint.controller;

import com.baomidou.mybatisplus.core.metadata.IPage;
import com.school.edupoint.config.EduContext;
import com.school.edupoint.model.Activity;
import com.school.edupoint.model.Gift;
import com.school.edupoint.response.Result;
import com.school.edupoint.service.GiftService;
import com.school.edupoint.service.StudentGiftService;
import com.school.edupoint.service.StudentService;
import com.school.edupoint.vo.ActivityVO;
import com.school.edupoint.vo.GiftVO;
import com.school.edupoint.vo.MessageVO;
import com.school.edupoint.websocket.MyTextWebSocketHandler;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import java.util.HashMap;
import java.util.Map;

@RestController
@RequestMapping("/api")
public class GiftController {
    @Autowired
    private EduContext eduContext;
    @Autowired
    private GiftService giftService;
    @Autowired
    private StudentService studentService;
    @Autowired
    private StudentGiftService studentGiftService;

    /**
     * 礼物分页
     * @param param
     * @return
     * @throws Exception
     */
    @PostMapping("/gift/page")
    public Result<IPage<Gift>> getGiftPage(@RequestBody Map<String, Object> param) throws Exception {
        String title = (String) param.get("title");
        int pageNum = (int) param.get("pageNum");
        int pageSize = (int) param.get("pageSize");
        System.out.println("当前第" + pageNum + "页");
        System.out.println("一页" + pageSize + "条数据");
        IPage<Gift> giftIPage = giftService.selectPage(title, pageNum, pageSize);
        System.out.println("活动分页数据为：" + giftIPage);
        return Result.success(giftIPage);
    }

    /**
     * 查询礼物详情
     *
     * @param giftId
     * @return
     */
    @GetMapping("/gift/info/getInfo/{giftId}")
    public Result<Gift> getInfo(@PathVariable Long giftId) {
        return Result.success(giftService.getInfo(giftId));
    }

    /**
     * 增加、修改礼物
     *
     * @param giftVO
     * @return
     */
    @PostMapping("/gift/save")
    public Result<GiftVO> saveGift(@RequestBody GiftVO giftVO) {
        System.out.println("保存接口前端传过来数据：" + giftVO.toString());
        return Result.success(giftService.save(giftVO));
    }

    /**
     * 上传礼物图片
     */
    @PostMapping("/gift/uploadphoto")
    public Result<Map<String, String>> uploadphoto(
            @RequestParam("photo") MultipartFile photo,
            @RequestHeader(value = "Authorization", required = false) String token
    ) throws Exception {
        System.out.println("上传接口前端传输数据" + photo);
        String photoUrl = giftService.uploadPhoto(photo);
        Map<String, String> data = new HashMap<>();
        data.put("url", photoUrl);

        return Result.success(data);

    }

    /**
     * 根据ID删除礼物
     *
     * @param
     * @return
     */
    @DeleteMapping("/gift/delete/{giftId}")
    public Result<Gift> deleteGiftId(@PathVariable("giftId") Integer id) {
        giftService.delete(id);
        return Result.success(null);
    }

    /**
     * 兑换礼物
     * @param param
     * @return
     */
    @PostMapping("/gift/cash")
    public Result<String> cash(@RequestBody Map<String, Object> param) {

        Integer giftId = (Integer) param.get("giftId");
        String receiveName=(String) param.get("receiveName");
        String receivePhone=(String) param.get("receivePhone");
        String address=(String) param.get("address");
        Integer studentId = eduContext.getStudent().getId();
        String cash = studentService.cash(giftId, studentId, receiveName, receivePhone, address);
        
        // 如果兑换成功，发送WebSocket通知给管理员
        if ("兑换成功".equals(cash)) {
            try {
                // 获取学生信息
                String studentName = eduContext.getStudent().getNickname();
                
                // 获取礼物信息
                Gift gift = giftService.getInfo(giftId.longValue());
                String giftName = gift != null ? gift.getName() : "未知礼物";
                
                MessageVO messageVO = new MessageVO();
                messageVO.setTitle("礼物兑换通知");
                messageVO.setContent("学生 " + studentName + " 兑换了礼物《" + giftName + "》");
                messageVO.setMessageType("GIFT_EXCHANGE");
                messageVO.setParam("{\"studentId\":" + studentId + ",\"studentName\":\"" + studentName + "\",\"giftId\":" + giftId + ",\"giftName\":\"" + giftName + "\"}");

                // 向所有管理员发送通知
                MyTextWebSocketHandler.broadcastToAllAdmins(messageVO);
                System.out.println("已向管理员发送礼物兑换通知：学生 " + studentName + "，礼物 " + giftName);
            } catch (Exception e) {
                System.err.println("发送WebSocket通知失败：" + e.getMessage());
                e.printStackTrace();
            }
        }
        
        return Result.success(cash);

    }






}
